package db

import (
	"fmt"

	"github.com/jinzhu/gorm"
)

type IMGroup struct {
	gorm.Model
	CreaterId uint
	Name      string
	Avatar    string
	Status    int
}

var Group IMGroup

func (g *IMGroup) Add() (groupId uint, err error) {
	group := g.CheckHaveGroupName(g.Name)
	if group.ID > 0 {
		groupId = group.ID
		err = fmt.Errorf("group %s existing", g.Name)
		return
	}

	err = dbIns.Create(g).Error
	if err != nil {
		return 0, err
	}
	return g.ID, nil
}

func (g *IMGroup) CheckHaveGroupName(name string) (data IMGroup) {
	dbIns.Where("name=?", name).First(&data)
	return
}

func (g *IMGroup) GetGroupNameByGroupId(id uint) string {
	var data IMGroup
	dbIns.Where("id=?", id).First(&data)
	return data.Name
}

func (g *IMGroup) GetDataById(id uint) (data IMGroup, err error) {
	err = dbIns.Where("id=?", id).First(&data).Error
	return
}

func (g *IMGroup) GetDataByName(name string) (data IMGroup, err error) {
	err = dbIns.Where("name=?", name).First(&data).Error
	return
}

func (g *IMGroup) Save() {
	dbIns.Save(g)
}
